import React from 'react'
import $ from 'jquery'
import {
    R_header_fixed
} from '../common/index'
import '../../plugins/city/js/LArea.js'
import {
    HttpService
} from '../../Tools'
import './style/business.scss'
import {Toast} from '../../Http'
import Chose from './img/chose.png'
import {
    Tips,
    imgUpload,
    ApiUploadImg,
    viewerImg,
    showLoading,
    showHiding,
    sxtUploadImgUse,
    haveEmoji

} from '../../Tools'
import Detele from './img/delete.png'

export  default  class BuinessForm extends React.Component {
    constructor(props) {
        super(props)
        this.allDatas;
        this.state = {
            flag: false,  //提示框是否显示
        }
        this.config = {
            isSure: false,
            isCancel: false,
            no: '取消',
            yes: '确定',
            content: '重新编辑将会撤销审核，请编辑后重新提交审核',
            yes_cb: () => {
            },
            no_cb: () => {
                this.setState({
                    flag: false
                });
            }
        };

        this.title = '创建商家'
        this.AreaRender = this.AreaRender.bind(this);


    }

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    componentWillMount() {
        this.AreaRender();
        const btoken = localStorage.btoken;
        const needAudit = this.props.params.needAudit;
        const rec = this;
        if (needAudit == 'reAudit') {
            this.title = '修改商家'
            $.ajax({
                url: '/jf/business/company/getByCompanyUser',
                type: "post",
                data: {
                    token: btoken
                },
                success: function (res) {
                    if (res.code == "10140") {
                        let refs = rec.refs;
                        let result = res.data;
                        rec.allDatas = result;
                        for (let v in refs) {
                            switch (v) {
                                case 'businessLicence' :
                                    document.getElementById('licenseS').src = Chose;
                                    break
                                case 'logo':
                                    document.getElementById('logoS').src = Chose
                                    break
                                case 'address':
                                    refs.address.value = result.address.split('&')[0]
                                    document.getElementsByClassName('detailAddress')[0].value = result.address.split('&')[1]
                                    break
                                case 'businessType':
                                    const type=['餐饮美食','亲子旅游','教育培训','运动健身','医疗健康','休闲娱乐'];
                                    let flag=false;
                                    let otype=document.getElementsByClassName('otherType')[0]
                                    for(let i=0;i<type.length;i++){
                                        if(result.businessType==type[i]){
                                            flag=true;
                                            refs.businessType.value = result.businessType;
                                            otype.style.display='none'
                                        }
                                    }
                                    if(!flag){
                                        refs.businessType.value = '其他';
                                        otype.value=result.businessType;
                                        otype.style.display='block'
                                }
                                    break
                                default:
                                    refs[v].value = result[v]
                                    break
                            }

                        }

                        //合作区域赋值
                        let areas = result.intentArea.split('&')
                        // document.getElementsByClassName('address')[0].value = areas[0]
                        for (var i = 0; i < areas.length-1; i++) {
                            let parent = document.getElementById('AddressBox')
                            const addInput = document.createElement("input");
                            const deleteimg = document.createElement('div');
                            deleteimg.className = 'deleteImg'
                            deleteimg.onclick = function () {
                                parent.removeChild(deleteimg.previousSibling)
                                parent.removeChild(deleteimg)
                            }.bind(parent)
                            addInput.setAttribute('disabled', true)
                            addInput.className = 'form-control address';
                            parent.appendChild(addInput);
                            parent.appendChild(deleteimg)
                            addInput.value = areas[i];

                        }
                        //图片赋值
                        document.getElementById('licenseS').src = result.businessLicence;
                        document.getElementById('licenseS').style.display = 'block';
                        document.getElementById('logoS').src = result.logo;
                        document.getElementById('logoS').style.display = 'block';

                    } else {
                        Tips(res.data)
                    }
                }

            })
        }
    }

    //选择区域渲染事件
    AreaRender() {
        HttpService.query({
            // url: 'src/Component/businessCenter/mock/city.min.json',
            url: '/business/json/city.min.json',
            sync: true,
            success: (data => {
                var area1 = new LArea();
                var area2 = new LArea();
                area1.init({
                    'trigger': '#city1',
                    'keys': {
                        id: 'id',
                        name: 'n'
                    }, //绑定数据源相关字段 id对应valueTo的value属性输出 name对应trigger的value属性输出
                    'type': 1, //数据源类型
                    'data': data //数据源
                });
                area2.init({
                    'trigger': ' #city2',
                    'keys': {
                        id: 'id',
                        name: 'n'
                    }, //绑定数据源相关字段 id对应valueTo的value属性输出 name对应trigger的value属性输出
                    'type': 1, //数据源类型
                    'data': data //数据源
                });
                area1.value = [0, 0, 0]; //控制初始位置，注意：该方法并不会影响到input的value
                area2.value = [0, 0, 0]; //控制初始位置，注意：该方法并不会影响到input的value
            })
        });
    }

    typeChange(e) {
        const type = e.target.value;
        let otherType=document.getElementsByClassName('otherType')[0];
        if (type == "其他") {
            otherType.style.display='block'
        }else{
            otherType.style.display='none'
        }
    }


    submitHandler(e) {
        e.preventDefault();
        const btoken = localStorage.btoken;
        let refs = this.refs;
        let data = {};
        var rec = this;
        const needAudit = this.props.params.needAudit;


        //获取form表单的值
        for (let i in refs) {
            // let refs = refs[i].value;
            data[i] = refs[i].value;
        }


        //判断手机号是否正确
        let patt =  /^\d{1,15}$/;
        let val = data.linkPhone;

        if (!patt.test(val)) {
            Toast.toast('手机号不正确，请重新输入');
            return false;
        }

        if(data.businessType=="其他"){
            let otherType=document.getElementsByClassName('otherType')[0].value;
            if(otherType){
                data.businessType=otherType
            }else{
                Toast.toast("请填写经营类别！")
                return
            }
        }
        //判断表单必填项
        for (let m in data) {
            if (data[m] == '') {
                Toast.toast(this.refs[m].nextSibling.innerHTML)
                return;
            }
        }

        //获取商户地址和详细地址
        const detailAddress = document.getElementsByClassName('detailAddress')[0].value;
        if (detailAddress == '') {
            Toast.toast('请详细地址！')
            return;
        }
        let address = data.address + '&' + detailAddress;

        //获取合作区域地址
        let addressInputs = document.getElementsByClassName('address');
        let addressValue = '';
        for (let n = 0; n < addressInputs.length; n++) {
            let adds = addressInputs[n].value;
            if (adds != '') {
                addressValue += adds + "&"
            }
        }

        if (addressValue.length < 1) {
            Toast.toast('请添加合作意向区域！')
            return;
        }
        let intentArea = addressValue;

        //获取商家logo
        let logo = document.getElementById('logo');
        let logoS = document.getElementById('logoS');
        if (logoS.src == '') {
            Toast.toast('请上传商家logo！')
            return;
        } else {
            if (logo.files.length > 0) {
                ApiUploadImg(logo.files[0], btoken, function (res, msg) {
                    data.logo = sxtUploadImgUse + '/images/' + res.status;
                })
            }
        }

        //获取商家营业执照
        let license = document.getElementById('license');
        let licenseS = document.getElementById('licenseS');
        if (licenseS.src == '') {
            Toast.toast('请上传营业执照！')
            return;
        } else {
            if (license.files.length > 0) {
                ApiUploadImg(license.files[0], btoken, function (res, msg) {
                    data.businessLicence = sxtUploadImgUse + '/images/' +res.status;
                })
            }
        }

        if (needAudit == 'reAudit') {
            const allData = this.allDatas;
            const change = ['name', 'businessType', 'linkPhone', 'linkPeople', 'linkPeopleJob', 'introduce']
            var changeData = {
                id: allData.id
            }
            for (let m = 0; m < change.length; m++) {
                if (allData[change[m]] != data[change[m]]) {
                    changeData[change[m]] = data[change[m]]
                }
            }

            if (logo.files.length > 0) {
                changeData.logo = data.logo
            }

            if (allData.address != address) {
                changeData.intentArea = address
            }


            if (license.files.length > 0) {
                changeData.businessLicence = data.businessLicence
            }

            if (allData.intentArea != intentArea) {
                changeData.intentArea = intentArea
            }
            if (!/^[\s+`~!@#$%^&*()\-=_+[\]{};'\\:"|,.<>/?·！￥…（）—【】；‘’、“”：，。《》、a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(changeData)) {
                Tips('提交内容有特殊字符')
                return
            }

            if( haveEmoji(JSON.stringify(changeData))){
                Toast.toast('提交内容有特殊字符')
                return
            }

            $.ajax({
                url: '/jf/business/company/update?token=' + btoken,
                type: "post",
                dataType: "json",
                data: JSON.stringify(changeData),
                headers: {'Content-Type': 'application/json'},
                success: function (res) {
                    if (res.code == 50006) {
                        Toast.toast(res.data)
                        rec.context.router.push('/businessIndex/1');
                    } else if (res.code == 50007) {
                        Toast.toast(res.data)
                    }
                }
            })


        } else {
            let res = {
                "name": data.name,
                "businessLicence": data.businessLicence,
                "linkPhone": data.linkPhone,
                "linkPeople": data.linkPeople,
                "linkPeopleJob": data.linkPeopleJob,
                "address": address,
                "intentArea": intentArea,
                "logo": data.logo,
                "introduce": data.introduce,
                "businessType": data.businessType
            }

            if (!/^[\s+`~!@#$%^&*()\-=_+[\]{};'\\:"|,.<>/?·！￥…（）—【】；‘’、“”：，。《》、a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(res)) {
                Tips('提交内容有特殊字符')
                return
            }

            if( haveEmoji(JSON.stringify(res))){
                Toast.toast('提交内容有特殊字符')
                return
            }

            $.ajax({
                url: '/jf/business/company/submit?token=' + btoken,
                type: "post",
                dataType: "json",
                data: JSON.stringify(res),
                headers: {'Content-Type': 'application/json'},
                success: function (res) {
                    if (res.code == 50006) {
                        Toast.toast(res.data)
                        rec.context.router.push('/businessIndex/1');
                    } else if (res.code == 50007) {
                        Toast.toast(res.data)
                    }
                }
            })
        }


    }


    delete() {
    }

    //添加合作区域
    areasClick(e) {
        const addArea = e.target.previousSibling.firstChild;
        const addValue = addArea.value;
        if (addValue == '') {
            Toast.toast('请选择合作意向区域！')
            return;
        }
        // e.target.nextSibling.style.marginBottom=0;
        const parent = e.target.parentNode;
        // if (parent.lastChild.className == 'deleteImg') {
        //     parent.lastChild.previousSibling.value = addValue
        // } else {
        //     parent.lastChild.value = addValue
        // }
        const addInput = document.createElement("input");
        const deleteimg = document.createElement('div');
        addInput.value = addValue
        deleteimg.className = 'deleteImg'
        deleteimg.onclick = function () {
            parent.removeChild(deleteimg.previousSibling)
            parent.removeChild(deleteimg)
        }.bind(parent)
        addInput.ref = "areas1";
        addInput.setAttribute('disabled', true)
        addInput.className = 'form-control address';
        parent.appendChild(addInput);

        parent.appendChild(deleteimg)


        addArea.value = "";
    }

    //logo上传的表单
    logoUpload(e) {
        let rct = this;
        let img = document.getElementById('logoS');
        var image = new Image();
        var picInput = e.target;
        image.src = window.URL.createObjectURL(e.target.files[0]);
        image.onload = function () {
            const imgwidth = image.width;
            const imgheight = image.height;
            if (imgheight == 200 && imgwidth == 200) {
                img.src = window.URL.createObjectURL(picInput.files[0]);
                img.style.display = 'block';
            } else {
                Toast.toast('请上传宽度为 200像素, 高度为200像素的图片！')
                return
            }
        };

    }

    //营业执照上传
    licenseUpload(e) {
        let rct = this;
        let img = document.getElementById('licenseS');
        img.src = window.URL.createObjectURL(e.target.files[0]);
        img.style.display = 'block';
    }


    render() {
        const {flag} = this.state;
        return (
            <div className="buinessForm">
                <div>
                    <R_header_fixed left="1" title={this.title}/>
                    <div className="form">
                        <form  onSubmit={this.submitHandler.bind(this)}>
                            <div className="group">
                                <label >企业名称：</label>
                                <input type="text" className="form-control" name="name" ref="name"/>
                                <span className="errorSpan">请填写企业名称</span>
                                <p>需与当地政府颁发的商业许可证书或企业注册证上的企业名称完全一致，信息审核审核成功后，企业名称不可修改。</p>
                            </div>
                            <div className="group">
                                <label >经营类别：</label>
                                <div className="form-control chose">
                                    <select name='type' id='type' ref='businessType'
                                            onChange={this.typeChange.bind(this)}>
                                        <option value="餐饮美食">餐饮美食</option>
                                        <option value="亲子旅游">亲子旅游</option>
                                        <option value="教育培训">教育培训</option>
                                        <option value="运动健身">运动健身</option>
                                        <option value="医疗健康">医疗健康</option>
                                        <option value="休闲娱乐">休闲娱乐</option>
                                        <option value="其他">其他</option>
                                    </select>
                                    <img src={Chose}/>
                                </div>
                                <input type="text" className="form-control otherType" name="" placeholder="请填写经营类别" />
                            </div>
                            <div className="group">
                                <label >联系人：</label>
                                <input type="text" className="form-control" name="linkPeople" ref="linkPeople"/>
                                <span className="errorSpan">请填写联系人！</span>
                            </div>
                            <div className="group">
                                <label >联系人职务：</label>
                                <input type="text" className="form-control" name="linkPeopleJob" ref="linkPeopleJob"/>
                                <span className="errorSpan">请填写联系人职务！</span>

                            </div>
                            <div className="group">
                                <label >联系电话：</label>
                                <input  className="form-control" name="linkPhone" ref="linkPhone" type="number"  />
                                <span className="errorSpan">请填写联系电话！</span>
                            </div>
                            <div className="group">
                                <label>商家地址:</label>
                                <div className="form-control chose">
                                    <input type="button" ref='address' id='city1'/>
                                    <span className="errorSpan">请填写商家地址！</span>
                                    <img src={Chose}/>
                                </div>
                                {/*<input type="button" className="form-control" ref='address' id='city1'*/}
                                {/*placeholder='下拉选择'/>*/}

                                <div className="detailAdress">
                                    <input type="text" className="form-control detailAddress" placeholder="请输入详细地址"
                                           name="detailAddress"/>
                                    <span className="errorSpan">请填写详细地址！</span>
                                </div>

                            </div>
                            <div className="group " id="AddressBox">
                                <label>合作意向区域:</label>
                                <div className="form-control chose">
                                    <input type="button" id='city2'/>
                                    <img src={Chose}/>
                                </div>
                                {/*<input type="button" className="form-control" id='city2' placeholder='下拉选择'/>*/}
                                <input type="button" className="addBtn" value='+点击添加'
                                       onClick={this.areasClick.bind(this)}/>
                                <label>合作意向区域:</label>
                                {/*<input type="text" className="form-control address" name="cooperation"*/}
                                       {/*disabled="disabled"/>*/}
                            </div>
                            <div className="group" style={{marginTop:'40px'}}>
                                <label >商家logo：</label>
                                <div className="upload">
                                    <input type="button" className="addBtn" value='点击上传'/>
                                    <input type="file" className="form-control fileinput" name="logo" id="logo"
                                           onChange={this.logoUpload.bind(this)}/>
                                    <img className="smallImg" id="logoS" alt="商家logo"/>
                                </div>
                            </div>
                            <div className="group">
                                <label >营业执照扫描件：</label>
                                <div className="upload">
                                    <input type="button" className="addBtn" value='点击上传'/>
                                    <input type="file" className="form-control fileinput" name="license" id="license"
                                           onChange={this.licenseUpload.bind(this)}/>
                                    <img className="smallImg" id="licenseS" alt="营业执照扫描件"/>
                                </div>
                            </div>

                            <div className="group">
                                <label >商家介绍：</label>
                                <textarea type="text" className="form-control" rows='3' maxLength='10000' placeholder="10000字以内"
                                          name="intro" ref="introduce"/>
                                <span className="errorSpan">请填写商家介绍！</span>
                            </div>
                            <div className="form-group submitAudit">
                                <button className="btn btn-default Btn" type="submit" >提交审核</button>
                            </div>
                        </form>
                    </div>
                </div>


            </div>
        )
    }
}
